package at.fhooe.im440.pandora.io;

import java.awt.event.*;

import at.fhooe.im440.pandora.core.Core;
import at.fhooe.im440.pandora.events.KeyPressedEvent;

public class InputManager implements KeyListener {

	private static final int NUM_KEY_CODES = 256;
	private Core core;
	private GameAction[] keyActions;

	public InputManager(Core core) {
		this.core = core;
		keyActions = new GameAction[NUM_KEY_CODES];
	}

	public void keyPressed(KeyEvent e) {

		if (e.getKeyCode() >= 0 && e.getKeyCode() < 256) {
			if (keyActions[e.getKeyCode()] != null)
				keyActions[e.getKeyCode()].press();
			core.eventManager.addEvent(new KeyPressedEvent(e.getKeyCode()));
		}
		e.consume();
	}

	public void keyReleased(KeyEvent e) {

		if (e.getKeyCode() >= 0 && e.getKeyCode() < 256) {
			// keysPressed[e.getKeyCode()] = false;
			if (keyActions[e.getKeyCode()] != null)
				keyActions[e.getKeyCode()].release();
		}
		e.consume();
	}

	@Override
	public void keyTyped(KeyEvent e) {
		e.consume();
	}

	/**
	 * Maps a GameAction to a specific key. The key codes are defined in
	 * java.awt.KeyEvent. If the key already has a GameAction mapped to it, the
	 * new GameAction overwrites it.
	 */
	public void mapToKey(GameAction gameAction, int keyCode) {
		keyActions[keyCode] = gameAction;
	}

}
